package boc.sx.gateway.socket.client.initializer;

import boc.sx.gateway.protocal.DefaultCodec;
import boc.sx.gateway.socket.client.handler.HttpClientHandler;
import boc.sx.gateway.socket.client.handler.SimpleClientHandler;
import boc.sx.gateway.socket.client.support.ChannelInitializerBuilder;
import boc.sx.gateway.socket.client.support.Protocol;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.string.StringDecoder;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/*
 * @author zmx
 * @date 2022/8/18 10:04
 */
@Component
@Scope("prototype")
@Protocol("simple")
public class HttpClientInitializer extends ChannelInitializer<SocketChannel> implements ChannelInitializerBuilder {

    public String requestPath;

    public Object msg;

    public String requestCode;

    public String acceptDataType;   //期望的数据格式

    public String sourceDataType;   //接受到的数据

    public HttpClientInitializer() {
    }

    public HttpClientInitializer(String requestCode, Object msg,String requestPath) {
        this.requestPath = requestPath;
        this.msg = msg;
        this.requestCode = requestCode;
    }

    @Override
    public ChannelInitializer config(String requestCode, Object msg,String requestPath){

        HttpClientInitializer initializer = new HttpClientInitializer(requestCode,msg,requestPath);
        return initializer;
    }

    /**
     * 初始化channel
     */
    @Override
    protected void initChannel(SocketChannel channel) {
        if( requestCode == null){
            return;
        }
        HttpClientHandler httpClientHandler = new HttpClientHandler(requestPath,requestCode,msg);
        channel.pipeline().addLast(new HttpClientCodec());
        //聚合
        channel.pipeline().addLast(new HttpObjectAggregator(1024 * 10 * 1024));
        //解压
        channel.pipeline().addLast(new HttpContentDecompressor());
        channel.pipeline().addLast(httpClientHandler);

    }
}
